package net.xt.testthread;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class TestDelayQueue {

    public static void main(String[] args) {
        DelayQueue<MyMessage> queue = new DelayQueue<>();

        // 添加元素
        queue.put(new MyMessage("消息1", System.currentTimeMillis(), 5000L));
        queue.put(new MyMessage("消息2", System.currentTimeMillis(), 3000L));
        queue.put(new MyMessage("消息3", System.currentTimeMillis(), 1000L));

        // 获取元素
        queue.forEach(myMessage -> {
            try {
                System.out.println(queue.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 自定义消息类，实现Delayed接口
     * 重写getDelay compareTo方法
     */
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    static class MyMessage implements Delayed {

        private String content;
        private long createTime;
        private long delayTime;

        @Override
        public long getDelay(TimeUnit unit) {
            // 延迟时间=创建时间+延迟时间-系统当前时间
            return createTime + delayTime - System.currentTimeMillis();
        }

        @Override
        public int compareTo(Delayed delayed) {
            MyMessage myMessage = (MyMessage) delayed;
            return Long.compare(this.delayTime, myMessage.delayTime);
        }
    }

}
